﻿using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System;

public partial class Runner
{
    void Download(PackageDef packageDef, string nupkgCacheFilePath, IEnumerable<string> additionalFeeds)
    {
        bool success = false;
        ExpectedException lastException = null;
        cacheCleanRequired = true;
        var sources = (new string[] { "http://packages.nuget.org" })
            .Union(additionalFeeds ?? new string[] { }).ToList();

        using (var webClient = new WebClient())
        {
            webClient.Credentials = CredentialCache.DefaultNetworkCredentials;

            foreach (string source in sources)
            {
                var address = string.Format("{0}/api/v2/package/{1}/{2}", source, packageDef.Id, packageDef.Version);
                string tempFileName = null;
                try
                {
                    tempFileName = Path.GetTempFileName();
                    WriteInfo("Downloading " + address);
                    webClient.DownloadFile(address, tempFileName);
                    File.Copy(tempFileName, nupkgCacheFilePath, true);
                    success = true;
                    break;
                }
                catch (WebException webException)
                {
                    if (tempFileName != null)
                    {
                        File.Delete(tempFileName);
                    }
                    lastException = new ExpectedException(string.Format("Failed to download '{0}' due to '{1}'. This package may no longer exist on the nuget feed or there is a problem with your internet connection.", address, webException.Message));
                }
            }

            if (!success)
            {
                throw lastException;
            }
        }
    }
}